package com.steak.concurrent.CompletableFuture;

import com.steak.concurrent.common.OrderInfo;
import com.steak.concurrent.common.R;

import java.util.concurrent.*;

/**
 * @author 刘牌
 * @Title:
 * @date 2022/3/2715:13
 */
public class PlaceOrderApi {

    //保存订单任务
    public static CompletableFuture<R> saveOrderTask(OrderInfo orderInfo){
        return CompletableFuture.supplyAsync(() -> saveOrder(orderInfo));
    }

    //扣减库存任务
    public static CompletableFuture<R> decreaseStockTask(OrderInfo orderInfo){
        return CompletableFuture.supplyAsync(() -> decreaseStockByCommodityId(orderInfo));
    }

    //增加积分任务
    public static CompletableFuture<R> increaseIntegralTask(OrderInfo orderInfo){
        return CompletableFuture.supplyAsync(() -> increaseIntegralByUserId(orderInfo));
    }

    public static void sendMsgToPhone(OrderInfo orderInfo){
        CompletableFuture.runAsync(() -> System.out.println("用户【"+orderInfo.getUserId()+"】，你已下单成功~~~~~~~~"));
    }

    //增加积分rpc接口
    public static R increaseIntegralByUserId(OrderInfo orderInfo){
        System.out.println("增加积分~~~~~~~~");
        //integralService.increaseIntegralByUserId(orderInfo.getUserId(),20);
        return new R(200,"增加积分成功",null);
    }

    //扣减库存rpc接口
    public static R decreaseStockByCommodityId(OrderInfo orderInfo){
        System.out.println("扣减库存~~~~~~~~");
        //stockService.decreaseStockByCommodityId(orderInfo.getCommodityId());
        return new R(200,"扣减库存成功",null);
    }

    //保存订单rpc接口
    public static R saveOrder(OrderInfo orderInfo){
        System.out.println("保存订单~~~~~~~~");
        //orderService.insert(orderInfo);
        return new R(200,"保存订单成功",null);
    }


    public static void main(String[] args) throws ExecutionException, InterruptedException, TimeoutException {
        OrderInfo orderInfo = new OrderInfo().setId("123455").setUserId("111111").setCommodityId("123321");
        CompletableFuture<R> orderTask = saveOrderTask(orderInfo);
        CompletableFuture<R> stockTask = decreaseStockTask(orderInfo);
        CompletableFuture<R> integralTask = increaseIntegralTask(orderInfo);
        sendMsgToPhone(orderInfo);
        if (orderTask.get().getCode() == 200 && orderTask.isDone()) System.out.println(orderTask.get().getMsg());
        if (stockTask.get().getCode() == 200 && stockTask.isDone()) System.out.println(stockTask.get().getMsg());
        if (integralTask.get().getCode() == 200 && integralTask.isDone()) System.out.println(integralTask.get().getMsg());
    }
}
